﻿using System;
using Microsoft.SharePoint;
using VH.SharePoint.Api.Entensions;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api
{
    public class MediaItemCollection : ObjectCollection<MediaItem>
    {
        internal MediaItemCollection(BlogWeb blog, Guid targetList) : base(blog, targetList)
        {
            this.Query = DefautQuery();
        }

        public override sealed SPQuery Query { get; protected set; }

        private SPQuery DefautQuery()
        {
            return new SPQuery
            {
                ViewAttributes = "Scope='Recursive'",
                RowLimit = 100,
                Query = "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy>"
            };
        }

        public MediaItem Add(MediaItemInforCreation mediaInfo)
        {
            using (new SPUnsafeUpdate(Blog.Web))
            {
                var folder = List.RootFolder.TryGetOrCreateRecurive(string.IsNullOrEmpty(mediaInfo.Url) ? Blog.MediaFolderName : mediaInfo.Url);
                var file = folder.Files.Add(mediaInfo.GetRelativeUrl(folder), mediaInfo.Content, mediaInfo.Overwrite);
                return file.Item;
            }
        }

        public MediaItem GetByFileName(String filename)
        {
            var query = DefautQuery();
            query.RowLimit = 1;
            query.Query = "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + filename + "</Value></Eq></Where>";
            var items = this.List.GetItems(query);
            if (items.Count > 0)
                return items[0];
            throw new SPException(filename+" is not found.");
        }
    }
}